import React, { useState, useEffect } from 'react';
import { 
  Box, Typography, Button, IconButton, Card, CardContent, 
  Dialog, DialogTitle, DialogContent, DialogActions, 
  TextField, Grid, Divider, Alert, CircularProgress,
  useTheme, alpha
} from '@mui/material';
import { 
  Add as AddIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  Business as BusinessIcon
} from '@mui/icons-material';
import { format } from 'date-fns';
import axios from 'axios';

interface Internship {
  id: number;
  company: string;
  position: string;
  start_date: string;
  end_date?: string;
  description?: string;
}

interface InternshipsProps {
  internships: Internship[];
  onUpdate: () => void;
}

const Internships: React.FC<InternshipsProps> = ({ internships, onUpdate }) => {
  const theme = useTheme();
  const [open, setOpen] = useState(false);
  const [editId, setEditId] = useState<number | null>(null);
  const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
  const [deleteId, setDeleteId] = useState<number | null>(null);
  const [loading, setLoading] = useState(false);
  const [success, setSuccess] = useState('');
  const [error, setError] = useState('');
  const [formData, setFormData] = useState({
    company: '',
    position: '',
    start_date: '',
    end_date: '',
    description: ''
  });

  const resetForm = () => {
    setFormData({
      company: '',
      position: '',
      start_date: '',
      end_date: '',
      description: ''
    });
    setEditId(null);
  };

  const handleOpen = () => {
    resetForm();
    setOpen(true);
  };

  const handleEdit = (internship: Internship) => {
    // 格式化日期为 YYYY-MM-DD 字符串
    const formatDate = (dateString: string | undefined) => {
      if (!dateString) return '';
      try {
        return dateString.split('T')[0];
      } catch (e) {
        return dateString;
      }
    };

    setFormData({
      company: internship.company,
      position: internship.position,
      start_date: formatDate(internship.start_date),
      end_date: formatDate(internship.end_date),
      description: internship.description || ''
    });
    setEditId(internship.id);
    setOpen(true);
  };

  const handleCloseDialog = () => {
    setOpen(false);
    resetForm();
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData({
      ...formData,
      [name]: value
    });
  };

  const handleDelete = (id: number) => {
    setDeleteId(id);
    setDeleteConfirmOpen(true);
  };

  const confirmDelete = async () => {
    if (deleteId === null) return;
    
    setLoading(true);
    setError('');
    
    try {
      await axios.delete(`/api/profile/internships/${deleteId}`);
      setSuccess('实习经历已成功删除');
      onUpdate();
      setDeleteConfirmOpen(false);
    } catch (err: any) {
      setError(err.response?.data?.message || '删除实习经历时出错');
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async () => {
    // 基本验证
    if (!formData.company || !formData.position || !formData.start_date) {
      setError('请填写必填字段');
      return;
    }

    setLoading(true);
    setError('');
    setSuccess('');

    try {
      if (editId) {
        // 更新现有实习经历
        await axios.put(`/api/profile/internships/${editId}`, formData);
        setSuccess('实习经历已成功更新');
      } else {
        // 添加新的实习经历
        await axios.post('/api/profile/internships', formData);
        setSuccess('实习经历已成功添加');
      }
      
      onUpdate();
      handleCloseDialog();
    } catch (err: any) {
      setError(err.response?.data?.message || '保存实习经历时出错');
    } finally {
      setLoading(false);
    }
  };

  // 格式化日期显示
  const formatDateDisplay = (dateString: string | undefined) => {
    if (!dateString) return '';
    try {
      return format(new Date(dateString), 'yyyy-MM-dd');
    } catch (e) {
      return dateString;
    }
  };

  // 获取时间段显示
  const getPeriodDisplay = (startDate: string, endDate?: string) => {
    const start = formatDateDisplay(startDate);
    const end = endDate ? formatDateDisplay(endDate) : '至今';
    return `${start} ~ ${end}`;
  };

  return (
    <Box>
      {success && (
        <Alert 
          severity="success" 
          sx={{ mb: 2 }}
          onClose={() => setSuccess('')}
        >
          {success}
        </Alert>
      )}
      
      {error && (
        <Alert 
          severity="error" 
          sx={{ mb: 2 }}
          onClose={() => setError('')}
        >
          {error}
        </Alert>
      )}
      
      <Box sx={{ display: 'flex', justifyContent: 'flex-end', mb: 2 }}>
        <Button 
          variant="contained" 
          color="primary" 
          startIcon={<AddIcon />}
          onClick={handleOpen}
        >
          添加实习经历
        </Button>
      </Box>
      
      {internships.length > 0 ? (
        <Box>
          {internships.map((internship) => (
            <Card 
              key={internship.id} 
              sx={{ 
                mb: 2, 
                boxShadow: '0 2px 8px rgba(0,0,0,0.08)',
                borderRadius: '10px',
                transition: 'transform 0.2s',
                '&:hover': {
                  transform: 'translateY(-2px)',
                  boxShadow: '0 4px 12px rgba(0,0,0,0.12)'
                }
              }}
            >
              <CardContent>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                  <Box sx={{ display: 'flex', alignItems: 'center' }}>
                    <BusinessIcon sx={{ mr: 1.5, color: theme.palette.primary.main }} />
                    <Box>
                      <Typography variant="h6" sx={{ fontWeight: 'bold' }}>
                        {internship.position}
                      </Typography>
                      <Typography variant="subtitle1" color="primary">
                        {internship.company}
                      </Typography>
                    </Box>
                  </Box>
                  
                  <Box sx={{ display: 'flex', alignItems: 'center' }}>
                    <Typography variant="body2" color="text.secondary" sx={{ mr: 2 }}>
                      {getPeriodDisplay(internship.start_date, internship.end_date)}
                    </Typography>
                    <IconButton
                      size="small"
                      onClick={() => handleEdit(internship)}
                      sx={{ mr: 0.5 }}
                    >
                      <EditIcon fontSize="small" />
                    </IconButton>
                    <IconButton
                      size="small"
                      onClick={() => handleDelete(internship.id)}
                      color="error"
                    >
                      <DeleteIcon fontSize="small" />
                    </IconButton>
                  </Box>
                </Box>
                
                {internship.description && (
                  <Typography variant="body2" sx={{ mt: 2, color: alpha(theme.palette.text.primary, 0.7) }}>
                    {internship.description}
                  </Typography>
                )}
              </CardContent>
            </Card>
          ))}
        </Box>
      ) : (
        <Box sx={{ 
          py: 4, 
          textAlign: 'center',
          bgcolor: 'background.paper',
          borderRadius: '10px',
          border: `1px dashed ${theme.palette.divider}`
        }}>
          <Typography color="text.secondary">
            暂无实习经历
          </Typography>
          <Button 
            variant="outlined" 
            startIcon={<AddIcon />} 
            sx={{ mt: 2 }}
            onClick={handleOpen}
          >
            添加实习经历
          </Button>
        </Box>
      )}
      
      {/* 添加/编辑对话框 */}
      <Dialog
        open={open}
        onClose={handleCloseDialog}
        fullWidth
        maxWidth="sm"
      >
        <DialogTitle>
          {editId ? '编辑实习经历' : '添加实习经历'}
        </DialogTitle>
        <DialogContent>
          <Grid container spacing={2} sx={{ mt: 0.5 }}>
            <Grid item xs={12}>
              <TextField
                fullWidth
                required
                label="公司名称"
                name="company"
                value={formData.company}
                onChange={handleChange}
                placeholder="例如：腾讯科技有限公司"
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                fullWidth
                required
                label="职位"
                name="position"
                value={formData.position}
                onChange={handleChange}
                placeholder="例如：前端开发实习生"
              />
            </Grid>
            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                required
                label="开始日期 (YYYY-MM-DD)"
                name="start_date"
                value={formData.start_date}
                onChange={handleChange}
                placeholder="例如：2023-06-01"
              />
            </Grid>
            <Grid item xs={12} sm={6}>
              <TextField
                fullWidth
                label="结束日期 (YYYY-MM-DD，留空表示至今)"
                name="end_date"
                value={formData.end_date}
                onChange={handleChange}
                placeholder="例如：2023-09-01"
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="实习内容描述"
                name="description"
                value={formData.description}
                onChange={handleChange}
                multiline
                rows={4}
                placeholder="描述你的主要工作内容、成就和收获"
              />
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseDialog}>取消</Button>
          <Button 
            onClick={handleSubmit} 
            variant="contained" 
            color="primary"
            disabled={loading}
          >
            {loading ? '保存中...' : '保存'}
          </Button>
        </DialogActions>
      </Dialog>

      {/* 删除确认对话框 */}
      <Dialog
        open={deleteConfirmOpen}
        onClose={() => setDeleteConfirmOpen(false)}
      >
        <DialogTitle>确认删除</DialogTitle>
        <DialogContent>
          <Typography>确定要删除此实习经历记录吗？此操作无法撤销。</Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteConfirmOpen(false)}>取消</Button>
          <Button 
            onClick={confirmDelete} 
            color="error" 
            variant="contained"
            disabled={loading}
          >
            {loading ? '删除中...' : '确认删除'}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default Internships; 